#include "UdpEvent.h"
#include "UtilityTH.h"

UdpEvent::UdpEvent()
{
    mSocket.bind(QHostAddress::Any, 8888);
    connect(&mSocket, &QUdpSocket::readyRead, this, &UdpEvent::Read);
}

void UdpEvent::Event()
{
    if(!m_clientHasAddr)
    {
        return;
    }

    unsigned char aa[7];
    aa[0] = 0x67;
    aa[1] = 0x00;
    aa[2] = 0xC1;
    aa[3] = 0x04;
    aa[4] = 0;
    aa[5] = CheckSum(&aa[2],3);
    aa[6] = 0xFB;
//    mSocket.write((char*)aa, 7);

    mSocket.writeDatagram((char*)aa,7, m_clientAddress, m_clientPort);

}


void UdpEvent::Read()
{
//    //读取串口数据
//    QByteArray readComData = serialport.readAll();
//    //将读到的数据显示到数据接收区的text中
//    if(readComData != nullptr)
//    {
//        printf("data[7] is %d\n",readComData.data()[7]);
//    }
//    //清除缓冲区
//    readComData.clear();

    QByteArray ba;
    while(mSocket.hasPendingDatagrams())
    {
        ba.resize(mSocket.pendingDatagramSize());
        mSocket.readDatagram(ba.data(), ba.size(),&m_clientAddress,&m_clientPort);
        m_clientHasAddr = true;
        printf("data[7] is %d\n",ba.data()[7]);
//        std::cout << ba.data() << std::endl;
    }
}
